

/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  query.fieldlist;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Vector;

import utility.Index;

//import utility.Input;
import dbmanager.DBManager;
import dbmanager.GetIdName;

public class Report_master implements Fieldlist
{
	String buffer[];
	String Querybuffer[];
	String object;
	String FIELDLIST="field";
	int Querycount=0;
	GetIdName gid;
	String reportName;
	Vector<Object> FieldVector;
	String ALIES="alies";
	String QUERY;
	StringBuffer finalbuffer= new StringBuffer(); 
	/**
	 * generate final buffer by finding all field  
	 * @return void
	 */
	@SuppressWarnings("unchecked")
	public void getResult() 
	{	
		String Field="";
		Vector< Object> Fieldlist =new Vector<Object>();
		try {
			Fieldlist = DBManager.getSelect("Select * from "+buffer[0], '1');
			//ResultSet rs = dbSql.getSelect("select "+Input.DATEFIELD+" from "+Querybuffer[0]);
			//if(rs.next())
			{
				Hashtable<Object, Object> table =new Hashtable<Object, Object>();

				//table.put("field",Input.DATEFIELD);
				//FieldVector.add(table);
			}
			//else
			{
				//rs = dbSql.getSelect("select "+Input.DATEFIELD+" from "+buffer[0]);
				//if(rs.next())
				{
		//			Hashtable<Object, Object> table =new Hashtable<Object, Object>();
					/*table.put("field",Input.DATEFIELD);
					FieldVector.add(table);*/
				//	table.put("field",Input.DATEFIELD);
				//	FieldVector.add(table);
				}
			}
			
		} catch (Exception e1) 
		{
			e1.printStackTrace();
		}
		for(int i=0;i<FieldVector.size();i++)
		{
			try
			{
				Hashtable<Object, Object> table = (Hashtable<Object, Object>) FieldVector.get(i);
				if(table.containsKey(ALIES))
				{
					String tempfield=gid.getItem(table.get(ALIES).toString());
					if(tempfield.equals("no$"))
						tempfield = table.get(ALIES).toString();
					finalbuffer.append(tempfield+"\t");
					String field = gid.getItem(table.get(FIELDLIST).toString());
					if(field.equals("no$"))
						field =table.get(FIELDLIST).toString();
					table.put(FIELDLIST, field);
					table.put(ALIES, tempfield);
					//finalbuffer.append(field+"\t");
					String name  = (table.get(FIELDLIST).toString().toLowerCase());
					//Field =Field+checkinFieldlist(Fieldlist, table, Querycount);
				/*	if(Fieldlist.contains(name))
						Field = Field + "p_" +(Querycount)+"." + name +  "as "+ tempfield +",";
					else	
						Field = Field +"p_" +(Querycount-1) + "." + name +  "as "+ tempfield +",";*/
				}	
				else
				{
					String field = gid.getItem(table.get(FIELDLIST).toString());
					if(field.equals("no$"))
						field =table.get(FIELDLIST).toString();
					table.put(FIELDLIST, field);
					finalbuffer.append(field+"\t");
				}
				Field =Field+checkinFieldlist(Fieldlist, table, Querycount-1);
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
		Field = Field.substring(0,Field.length()-1);
		String tempQuery=QUERY;
		QUERY = QUERY.substring(0, tempQuery.indexOf("distinct")+tempQuery.indexOf("distinct")+1)+ " " +Field + QUERY.substring(tempQuery.indexOf("distinct")+1+tempQuery.indexOf("distinct"), QUERY.length());
		
		finalbuffer.append("\n");
	}
	/**
	 * return buffer which is String array  
	 * @return buffer which is result Rate_master class 
	 */
	@SuppressWarnings("unchecked")
	public String[] getbuffer() 
	{
		try {
			ResultSet rs = DBManager.getSelect(QUERY);
			while(rs.next())
			{
					for(int i=0;i<FieldVector.size();i++)
					{
						try 
						{
							Hashtable<Object, Object> table = (Hashtable<Object, Object>) FieldVector.get(i);
							String value = rs.getString(table.get(FIELDLIST).toString());
							finalbuffer.append(value+"\t");
						}
						catch (Exception e) 
						{
							finalbuffer.append("null\t");
						}
					}
					finalbuffer.append("\n");
				}
				
		}
		catch (SQLException e1) 
		{
			e1.printStackTrace();
		}
		buffer = (finalbuffer.toString()).split("\n");
		return buffer;
	}
	/**
	 * set database object and find master id of Field
	 * @param db is database object
	 */
	public void initFieldList() 
	{
	  gid = new GetIdName();
	}
	/**
	 * set field object 
	 * @param Object is Field object
	 */
	public void setFieldVector(Vector<Object> FieldVector)
	{
		this.FieldVector = FieldVector;
	}
	/**
	 * set buffer which Strng array
	 * @param buffer[] 
	 */
	public void setbuffer(String[] buffer) 
	{
		this.buffer = buffer;
	}
	public static void main(String[] args) 
	{
		Rate_master rm = new Rate_master();
		rm.initFieldList();
		String temp[]={"id	Item	Rate	Unit	FD	TD	BuySell	UserGroup",	
				"3049	4121	14.00000000	Kg	2007-05-16 16:24:24	0000-00-00 00:00:00	217	5693",	
				"1623	4121	14.00000000	Kg	2007-05-16 16:24:25	0000-00-00 00:00:00	217	5694",	
				"4475	4121	14.00000000	Kg	2007-05-16 16:24:26	0000-00-00 00:00:00	217	5695"};
			
		rm.setbuffer(temp);
		//rm.setObject("6259");
		rm.getResult();
		 temp=rm.getbuffer();
		for(int i=0;i<temp.length;i++)
		{
			System.out.println(temp[i]);
		}
	}
	/**
	 * generate final buffer   <p> when process is add in report_master then addreport method is called.
	 * addreport method call getresult method <p>
	 */
	public void addReport() 
	{
		getResult();
	}
	public void setReportName(String reportName) 
	{
		this.reportName =reportName;
	}
	/**
	 * generate final buffer   <p> when process is mod in report_master then updatereport method is called.
	 * updatereport method call getresult method <p>
	 */
	public void updateReport() 
	{
		getResult();	
	}
	
	public String getQuery() 
	{
		return QUERY;
	}
	public void setQuery(String Query) 
	{
		this.QUERY = Query;	
	}
	
	public void setQuerybuffer(String[] Querybuffer) 
	{
		this.Querybuffer = Querybuffer;
	}
	public void setQueryCount(int count) 
	{
	 this.Querycount = count; 	
	}	
	
	public String checkinFieldlist(Vector<Object> Fieldlist,Hashtable<Object, Object> table,int Querycount)
	{
		String Field= table.get(FIELDLIST).toString().toLowerCase();
		String Result = "";
		
		if(Fieldlist.contains(Field))
		{	
			if(table.containsKey(ALIES))
			{
				Result =  "p_" +(Querycount)+"." + Field  +   " as "+ table.get(ALIES) +",";
				table.put(FIELDLIST, table.get(ALIES));
				return Result;
			}	
			else
			{	
				Result = "p_" +(Querycount)+"." +Field + ",";
				return Result;
			}	
		}	
		else
		{
			for(int i=0;i<Fieldlist.size();i++)
			{
				String field= Fieldlist.get(i).toString().toLowerCase();
				if(field.contains(Field))
				{
					if(table.containsKey(ALIES))
					{	
						int index=getFieldIndex(Field, field);
						Result = Field.substring(0, index) + "p_" + (Querycount) + "."+  Field.substring(index, Field.length()) + " as "+ table.get(ALIES)+",";
						table.put(FIELDLIST, table.get(ALIES));
						return Result;
					}
					else
					{
						int index=getFieldIndex(Field, field);
						Result = Field.substring(0, index) + "p_" + (Querycount) + "."+  Field.substring(index, Field.length())+",";
						return Result;
					}	
				}
					
			}
		}
		if(!Field.contains("'"))
		{	
		if(table.containsKey(ALIES) )
		{
			Result =  "p_" +(Querycount-1)+"." + Field  +   " as "+ table.get(ALIES) +",";
			table.put(FIELDLIST, table.get(ALIES));
		}	
		else
			Result = "p_" +(Querycount-1)+"." +Field + ",";
		}
		else
		{
			for(int i=0;i<Fieldlist.size();i++)
			{
				String field= Fieldlist.get(i).toString();
				if(Field.contains(field))
				{
					if(table.containsKey(ALIES))
					{	
						int index=getFieldIndex(Field, field);
						Result = Field.substring(0, index) + "p_" + (Querycount-1) + "."+  Field.substring(index, Field.length()) + " as "+ table.get(ALIES)+",";
						table.put(FIELDLIST, table.get(ALIES));
						return Result;
					}
					else
					{
						int index=getFieldIndex(Field, field);
						Result = Field.substring(0, index) + "p_" + (Querycount-1) + "."+  Field.substring(index, Field.length())+",";
						return Result;
					}	
				}
					
			}
		
		}	
		return Result;
	}
	public int getFieldIndex(String Field,String indexfield)
	{
		if(!Field.contains("'"))
		{
			return Field.indexOf(indexfield);
		}	
		else
		{
			int index = Field.indexOf("'");
			if(index>0)
			{
				String temp = Field.substring(0,index);
				if(temp.contains(indexfield))
					return temp.indexOf(indexfield);
			}
			else
			{
				index = Field.lastIndexOf("'");
				String temp = Field.substring(index,Field.length());
				if(temp.contains(indexfield))
					return index+temp.indexOf(indexfield);
			}	
		}	
		return -1;	
			
	}
}
